package com.io.example.demoparent.service.impl;

import com.io.example.demoparent.bo.BizEvent;
import com.io.example.demoparent.listener.EventSubscriber;
import com.io.example.demoparent.service.BizEventListener;
import com.io.example.demoparent.service.EventEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;

/**
 * @program: demo-project
 * @ClassName EventEngineImpl
 * @description:
 * @author: 宠儿
 * @create: 2024−09-05 23:44
 * @Version 1.0
 **/
@Component
public class EventEngineImpl implements EventEngine {

    Logger logger = LoggerFactory.getLogger(EventEngineImpl.class);
    /**
     * 异步执行器。也系统需要自行定义线程池
     */
    private Executor bizListenerExecutor;

    /**
     * 是否异步，默认为false
     */
    private boolean async;

    /**
     * 订阅端 KEY是TOPIC，VALUES是监听器集合
     */
    private Map<String, List<BizEventListener>> bizSubscribers = new HashMap<>(16);



    @Override
    public void publishEvent(BizEvent event) {
        List<BizEventListener> bizEventListeners = bizSubscribers.get(event.getTopic());
        if (CollectionUtils.isEmpty(bizEventListeners)) {
            logger.info("publishEven事件为空");
            return;
        }
        bizEventListeners.forEach(bizEventListener -> {
            if (async){
                bizListenerExecutor.execute(new EventSubscriber(bizEventListener,event));
            }else {
                bizEventListener.onEvent(event);
            }
        });
    }

    public Executor getBizListenerExecutor() {
        return bizListenerExecutor;
    }

    public void setBizListenerExecutor(Executor bizListenerExecutor) {
        this.bizListenerExecutor = bizListenerExecutor;
    }

    public boolean isAsync() {
        return async;
    }

    public void setAsync(boolean async) {
        this.async = async;
    }

    public Map<String, List<BizEventListener>> getBizSubscribers() {
        return bizSubscribers;
    }

    public void setBizSubscribers(Map<String, List<BizEventListener>> bizSubscribers) {
        this.bizSubscribers = bizSubscribers;
    }
}
